import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { withRouter, Link } from 'react-router-dom';
import { message, Radio, Breadcrumb, Spin } from 'antd';
import runningImg from '../images/running.png';
import stopImg from '../images/stop.png';
import { NODE_NAME } from '@util/constants';
import NodeTrend from './components/node-trend';
import NodeTable from './components/node-table';
import { getNodeDetail, getNodeVersion } from '@api/nodes';
import moment from 'moment';
import _ from 'lodash';
import './index.less';

const prefixCls = 'node-detail';
class NodeDetail extends Component {
  constructor(props) {
    super(props);
    this.state = {
      chartData: [],
      tableData: [],
      latestData: {},
      dataScope: 'days',
      spinning: false,
      statusList: []
    };
    this.nodeIp = props.match.params.ip;
    this.pollingTimer = null;
  }

  componentDidMount() {
    this.getNodeDetail('days');
    this.getNodeStutas();
    this.pollingData();
  }

  componentWillUnmount() {
    window.clearInterval(this.pollingTimer);
  }

  getNodeDetail = scope => {
    const created = moment()
      .subtract(1, scope)
      .format('YYYY-MM-DD HH:mm:ss');
    getNodeDetail({ ip: this.nodeIp, created })
      .then(res => {
        const chartData = _.get(res, 'data.data.trendResult', []);
        const tableData = _.get(res, 'data.data.tableResult', []);
        const latestData = _.last(chartData);
        this.setState({ chartData, tableData, latestData });
      })
      .catch(() => {
        message.error('获取节点详情失败');
      });
  };

  getNodeStutas = () => {
    this.setState({ spinning: true });
    getNodeVersion()
      .then(res => {
        const statusList = _.get(res.data.data, 'slaves', []);
        this.setState({ statusList, spinning: false });
      })
      .catch(() => {
        this.setState({ spinning: false });
        // eslint-disable-next-line
        console.error('获取节点信息失败');
      });
  };

  pollingData() {
    this.pollingTimer = window.setInterval(() => {
      const { dataScope } = this.state;
      this.getNodeDetail(dataScope);
      this.getNodeStutas();
    }, 180000);
  }

  onDataScopeChange = e => {
    const dataScope = e.target.value;
    this.setState({ dataScope }, () => this.getNodeDetail(dataScope));
    window.clearInterval(this.pollingTimer);
    this.pollingData();
  };

  render() {
    const { chartData, tableData, latestData, dataScope, spinning, statusList } = this.state;
    const type = _.get(latestData, 'type');
    const status = _.get(
      _.find(statusList, i => i.host === this.nodeIp.replace(/-/g, '.')),
      'device_id',
      false
    );
    return (
      <div className={prefixCls}>
        <div className="bread">
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/system-config/node-manage">节点管理</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              <span style={{ fontWeight: 600 }}>节点详情</span>
            </Breadcrumb.Item>
          </Breadcrumb>
        </div>
        <Spin spinning={spinning}>
          <div className={`${prefixCls}-content node-chart`}>
            <div className={`${prefixCls}-title`}>设备状况变化趋势图</div>
            <div className={`${prefixCls}-chart-header ${type}`}>
              <div className={`${prefixCls}-chart-header-message`}>
                <div>
                  <div style={{ color: '#1E1F23' }}>{this.nodeIp.replace(/-/g, '.')}</div>
                  <span>{NODE_NAME[type] || ''}</span>
                </div>
                <div>
                  <span style={{ margin: '0 12px' }}>{status ? '运行中' : '无法连接'}</span>
                  <div className={`${prefixCls}-status ${status ? 'running' : ''}`}>
                    <img src={status ? runningImg : stopImg} width="24px" />
                  </div>
                </div>
              </div>
              <div>
                <Radio.Group value={dataScope} onChange={this.onDataScopeChange}>
                  <Radio.Button value="days">最近24小时</Radio.Button>
                  <Radio.Button value="hours">最近60分钟</Radio.Button>
                </Radio.Group>
              </div>
            </div>
            <div className={`${prefixCls}-content-chart`}>
              <NodeTrend data={chartData} />
            </div>
          </div>
          <div className={`${prefixCls}-content node-table`}>
            <div className={`${prefixCls}-title`}>设备状况记录</div>
            <NodeTable data={tableData} />
          </div>
        </Spin>
      </div>
    );
  }
}

NodeDetail.propTypes = {
  match: PropTypes.object
};

export default withRouter(NodeDetail);
